import util from "../../../../utils/util.js";
import api from "../../../../common/api.js";
import {
  xstShare
} from "../../../../common/subscribe.js";
import p from "../../../../utils/platform.js";
import {
  insertHouseMaterialDownLoadLog
} from "../../../../common/log.js";
import constant from "../../../../common/constant.js";
import {
  cooperationBehavior
} from "../../../../behaviors/cooperation.js";
import {
  houseInfoBehavior
} from "../../../../behaviors/houseInfo.js";
import {
  userInfoBehavior
} from "../../../../behaviors/userInfo.js";
import {
  httpUrlCheck
} from "../../../../utils/utilsNew.js";

const config = require("../../../../utils/config.js");

var app = getApp();
/** gio埋点 */
const _map = {
  NEWHOUSE: constant.XIN_FANG,
  RENT: constant.CHU_ZU,
  SALES: constant.ER_SHOU,
};

Page({
  behaviors: [cooperationBehavior, houseInfoBehavior, userInfoBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    isVmShow: false, //虚拟电话弹层
    fn: "", //对应的会员功能
    vrUrl: "",
    isLoadHouseDone: false, //视频下载完成
    isLoadingHouse: false, //下载视频中
    videoOption: false, //下载视频的弹窗
    menuId: "", //操作的权限按钮
    moreOption: false, //更多功能开关
    moreDownload: false, //下载房源素材
    vrTab: 1,
    vr: false,
    vrdown: false,
    // showMoreOptions: true,
    showMoreOptions: false,
    pyqVisible: false,
    memberOption: false,
    currentTabState: 0,
    tabList: config.tabList,
    reason: "", //下架理由
    time: "", //下架时间
    widthVi: app.globalData.windowHeight,
    isUpdate: false, //有没有修改房源详情
    friendsShowDialog: false,
    pyqmodal: false, //点击朋友圈分享后的弹窗
    isPageShow: false, //页面等数据请求完成再显示
    currentSwiper: 0, //轮播图当前位置
    tagName: "", //轮播图标签
    showDialog: false,
    listTabShowDialog: false,
    contactShowDialog: false,
    shareShowDialog: false,
    houdelid: "", //房源ID  (此处应该是 合作房源id 用了老页面所以没改)
    detailContent: "", //房源详情
    markers: [],
    from: true,
    loadSeccess: false,
    houseTypes: "",
    copyText: "",
    counts: 0,
    shorturlL: "",
    authenticationList: ["真实存在", "真实在售", "真实可合作"],
    corporateHousing: ["专人核验", "品质保障"],
    jjrVO: {}, //经纪人信息

    // 0610合作房源优化
    useridTmp: '', //被举报人id
    houseidTmp: '', //房源信息id
    isShowdajiaPng: true, //判断打假按钮是否显示
    showMap: false, //默认不展示地图
    hmCooperatioonNearByInfoVO: [],
    houseTime: '',
    tagList: [], //标签
    lightSpot: [],
    hmCooperation: '', //数据检测
    phoneCooperationId: '', //拨打虚拟号需要的CooperationId
    unionid:'', //im聊天需要的参数
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    app.globalData.loginPromise.then(() => {
      app.mobileLogin(false, '', false)
        .then(() => {
          this.setData({
            cooperationId: options.cooperationId
          });
          this.getHouseInfo();
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({
              url: "/pages/house/RentalHouseDetail/teamworkHouseDetail/teamworkHouseDetail?cooperationId=" + options.cooperationId
            });
          };
        })
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面

    try {
      const type = that.data.detailContent.houDelVO.delegationType;
      if (type == "SALES") {
        wx.setStorageSync("currentStatus", 1);
      } else if (type == "RENT") {
        wx.setStorageSync("currentStatus", 2);
      }
    } catch (error) {
      
    }

    if (prevPage && prevPage.setData) {
      prevPage.setData({
        isUpdate: true,
      });
    }

    wx.setStorageSync("boole", false);
    var houdelid = wx.getStorageSync("houdelid");
    if (houdelid == "2") {
      wx.removeStorageSync("houdelid");
      wx.navigateBack({
        delta: 2,
      });
    }

    app.globalData.mapTabStatusIndex = 0;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    let sessionUser = getApp().globalData.sessionUser;
    let agentId = sessionUser.id;
    const {
      detailContent,
      cooperationId
    } = this.data
    const {
      houImageVO,
      houDelVO
    } = detailContent || {}
    let buildSize = houDelVO.buildSize ? houDelVO.buildSize + '㎡' : '';
    let price = houDelVO.delegationType === "SALES" ? `${houDelVO.totalPrices ? houDelVO.totalPrices / 10000 : 0}` : `${houDelVO.totalPrices || 0}`
    let unit = houDelVO.delegationType === "SALES" ? '万' : '元/月'
    let result = {
      title: houDelVO.title? houDelVO.title: `${houDelVO.resblockName || ''} ${houDelVO.room || 0}室${houDelVO.hall || 0}厅 ${buildSize} ${price ? price + unit : ''}`,
      path: `/pages/house/RentalHouseDetail/teamworkHouseDetail/teamworkHouseDetail?cooperationId=${cooperationId}&agentId=${agentId}`,
      imageUrl: houImageVO && houImageVO.length ? houImageVO[0].url : '',
    }
    return result
  },

  //获取房源详情
  getHouseInfo() {
    const that = this,
      bannerList = [];
    this.getInfoByCooperationId(that.data.cooperationId, true).then((content) => {
      this.checkCooperationStatus(content.hmCooperationDelVO.cooperationDown)
      content.houDelVO = content.hmCooperationDelVO;
      content.houDelVO.id = content.houDelVO.delId;
      wx.gio("setPage", {
        [constant.ROOM_TYPE_PVAR]: _map[content.houDelVO.delegationType],
      });

      for (var k in content.houImageVO) {
        bannerList.push(content.houImageVO[k].url);
      }
      this.uploadVisitorLog({
        cooperationId: that.data.cooperationId,
        delId: content.hmCooperationDelVO.delId || ''
      })
      that.setData({
        houdelid: content.hmCooperationDelVO.delId,
        houseTypes: content.hmCooperationDelVO.delegationType,
        markers: [{
          id: 0,
          latitude: content.houDelVO.lat,
          longitude: content.houDelVO.lng,
          title: content.houDelVO.addr,
          callout:{
            content:content.houDelVO.addr,
            display:'ALWAYS',
            padding:8,
            bgColor:'#fff',
            fontSize:'24rpx',
            color:'#333333',
          },
        }, ],
        bannerList: bannerList,
        detailContent: content,
        tagName: content.houImageVO.length > 0 ? content.houImageVO[that.data.currentSwiper].tagName : "",
        isPageShow: true,
        loadSeccess: true,
        time: that.timestampToTime(content.houDelVO.changeTime),
        vr: (content.hmDelSummaryInfo.houSubType == 1 && content.hmDelSummaryInfo.houSubTypeState == 10) ||
          (content.hmDelSummaryInfo.houSubType == 1 && content.hmDelSummaryInfo.houSubTypeState == 1) ?
          true : false,
        vrdown: content.hmDelSummaryInfo.houSubType == 1 &&
          (content.hmDelSummaryInfo.houSubTypeState == 0 || content.hmDelSummaryInfo.houSubTypeState == -1) ?
          true : false,
        jjrVO: this.formatAuthenticatedInfo(content.jjrVO),
        hmCooperatioonNearByInfoVO: content.hmCooperatioonNearByInfoVO, //附近可合作
        hmCooperation: content.hmCooperationAuthenticityCheck, //数据检测
      });
      //自己计算的更新时间 finalConfirmTime 和houseInfoUpdateTime谁大取谁
      let finalConfirmTime = content.houseCooperation.finalConfirmTime
      let houseInfoUpdateTime = content.houseCooperation.houseInfoUpdateTime
      let newTime = new Date().getTime()
      if (finalConfirmTime - houseInfoUpdateTime < 0) {
        let showTime = (newTime - houseInfoUpdateTime) / 86400000
        this.setData({
          houseTime: showTime
        })
      } else {
        let showTime = (newTime - finalConfirmTime) / 86400000
        this.setData({
          houseTime: showTime
        })
      }

      // 自己拼接tagListTmp数据
      let tagListTmp = []
      let direction = this.data.detailContent.hmCooperationDelVO.direction //朝向
      let buildNumNew = this.data.detailContent.hmCooperationDelVO.buildNumNew //楼层
      let floorHeight = this.data.detailContent.hmCooperationDelVO.floorHeight //楼高
      let houYears = this.data.detailContent.hmCooperationDelVO.houYears //满五
      let unique = this.data.detailContent.hmCooperationDelVO.unique ||'' // 是否唯一  2不唯一  1唯一
      if (unique && unique !== undefined && unique !== '') {
        if (unique == 2) {
          unique = '不唯一'
        } else {
          unique = '唯一'
        }
      }
      if (direction && direction !== '' && direction !== undefined) {
        direction = "朝向" + direction
        tagListTmp.push(direction)
      }
      if (floorHeight && floorHeight !== undefined && floorHeight !== '') {
        floorHeight = floorHeight + '楼'
        tagListTmp.push(floorHeight)
      } else {
        if (buildNumNew && buildNumNew !== undefined && buildNumNew !== '') {
          tagListTmp.push(buildNumNew)
        }
      }
      if (houYears && houYears !== undefined && houYears !== '') {
        houYears = houYears + unique
        tagListTmp.push(houYears)
      }
      that.setData({
        tagList: tagListTmp,
        unionid: that.data.jjrVO.unionId || app.globalData.testUserID
      })
      wx.showShareMenu({
        withShareTicket: true,
      });
      that.getCount();
      if (content.hmDelSummaryInfo.videoMaterial) {
        that.getOssfiles();
      }
    })
  },

  swiperChange(e) {
    const that = this,
      currentSwiper = e.detail.current;
    const tagName = that.data.detailContent.houImageVO[currentSwiper].tagName;
    this.setData({
      currentSwiper: currentSwiper,
      tagName: tagName,
    });
  },

  callPhone(e) {
    var num = e.currentTarget.dataset.phonenum;
    wx.makePhoneCall({
      phoneNumber: num,
    });
  },

  toggleListTabDialog() {
    this.setData({
      listTabShowDialog: !this.data.listTabShowDialog,
    });
  },

  toggleContacTabDialog() {
    this.setData({
      contactShowDialog: !this.data.contactShowDialog,
    });
  },

  toggleShareTabDialog() {
    this.setData({
      shareShowDialog: !this.data.shareShowDialog,
      friendsShowDialog: false,
      pyqmodal: false,
    });

    if (this.data.shareShowDialog) {
      xstShare();
    }
  },

  toggleDialog(e) {
    var current = e.currentTarget.dataset.current;
    if (!current) {
      current = this.data.current;
      this.setData({
        showDialog: false,
      });
    } else if (current == this.data.current) {
      this.setData({
        showDialog: !this.data.showDialog,
      });
    } else {
      this.setData({
        showDialog: true,
      });
    }
    if (current) {
      this.setData({
        current: current,
      });
    } else {
      this.setData({
        current: this.data.current,
      });
    }
  },

  //跳转小区详情
  // goHousingEstateDetail() {
  //   wx.navigateTo({
  //     url: "/pages/house/housingEstateDetail/housingEstateDetail",
  //   });
  // },

  // 去充值页面
  goToMemberCentre() {
    wx.navigateTo({
      url: "/pages/mine/memberCentre/memberCentre",
    });
  },

  //无效房源
  goFailRoom() {
    const id = this.data.detailContent.houDelVO.id;
    var that = this;
    wx.showModal({
      title: "提示",
      content: "您确定将该房源标记为无效房源吗",
      confirmText: "确定",
      cancelText: "取消",
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: "加载中",
          });
          api.houseFail(id, {}, (res) => {
            wx.hideToast();
            var pages = getCurrentPages();
            var currPage = pages[pages.length - 1]; //当前页面
            var prevPage = pages[pages.length - 2]; //上一个页面
            const option = {
              type: that.data.houseTypes,
            };
            wx.navigateBack();
            prevPage.backRefash && prevPage.backRefash(option);
          });
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },

  //跳转修改房源
  goRentalHouseModify() {
    wx.navigateTo({
      url: "/pages/addHouse/infoEntryHouse/infoEntryHouse?houDelId=" + this.data.detailContent.houDelVO.id + "&flag=0",
    });
  },

  // 时间戳转换成日期
  timestampToTime(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + "/";
    var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "/";
    var D = date.getDate() + " ";
    var h = date.getHours() + ":";
    var m = date.getMinutes() + ":";
    var s = date.getSeconds();
    return Y + M + D;
  },

  saveImage(img) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: img,
        success: function ({
          path
        }) {
          wx.saveImageToPhotosAlbum({
            filePath: path,
            success: () => {
              resolve();
            },
            fail: (err) => {
              console.log("保存图片失败", err, path);
              resolve();
            },
          });
        },
        fail: () => {
          console.log("读取图片信息失败", err);
          resolve();
        },
      });
    });
  },

  saveImageAndroid(img) {
    return new Promise((resolve, reject) => {
      let filePath = wx.env.USER_DATA_PATH + "/" + Date.now() + ".jpg";
      wx.downloadFile({
        url: img,
        filePath,
        success: ({
          filePath
        }) => {
          wx.saveImageToPhotosAlbum({
            filePath,
            success: () => {
              resolve();
              let fileMgr = wx.getFileSystemManager();
              fileMgr.unlink({
                filePath,
                success: function (r) {
                  console.log("删除缓存ok", r);
                },
              });
            },
            fail: (err) => {
              console.log("保存图片失败", err, filePath);
              resolve();
            },
          });
        },
        fail: () => {
          console.log("读取图片信息失败", err);
          resolve();
        },
      });
    });
  },

  // 查询是否有下载图片的权限
  handleMemberDownLoadImgs(e) {
    api.getMemberPower({}, (res) => {
      if (res.data.isSuccess) {
        wx.setStorageSync("memberInfo", res.data.content.rows);
      }
      let menuId = e.currentTarget.dataset.id;
      let memberInfo = wx.getStorageSync("memberInfo");
      let downLoadImgs = memberInfo.find((element) => element.menuId == menuId);
      switch (menuId) {
        case "4c75216b479d4ba894e35e14549ca355":
          this.setData({
            fn: "下载无水印图片",
          });
          break;
        case "73ed001b790d4d1cb3e1f74a88756669":
          this.setData({
            fn: "下载全景图",
          });
          break;
        case "f18a0d92aec4499f8866cff3d7226c47":
          this.setData({
            fn: "VR下载",
          });
          break;
        case "60e6298af0b24f9db9af005e11e8e87a":
          this.setData({
            fn: "合成全景图",
          });
          break;
        case "5a634e15be20415c854056e30e49545d":
          this.setData({
            fn: "下载视频",
          });
          break;
        case "cb97dc7641fc482c805d42f83661c1c0":
          this.setData({
            fn: "VR转视频",
          });
          break;
      }

      this.setData({
        releaseNumber: downLoadImgs.dayNumber,
        totalNumber: downLoadImgs.totalNumber,
        menuId,
        dayNumbered: downLoadImgs.dayNumbered,
        totalNumbered: downLoadImgs.totalNumbered,
        statue: downLoadImgs.statue,
      });
      switch (menuId) {
        case "4c75216b479d4ba894e35e14549ca355":
          this.hanldeDownLoadImgs();
          break;
        case "73ed001b790d4d1cb3e1f74a88756669":
          this.goToPanoramagram();
          break;
        case "f18a0d92aec4499f8866cff3d7226c47":
          this.vrDownLoad();
          break;
        case "60e6298af0b24f9db9af005e11e8e87a":
          this.goToComposite();
          break;
        case "5a634e15be20415c854056e30e49545d":
          this.handleVideo();
          break;
        case "cb97dc7641fc482c805d42f83661c1c0":
          this.goToVideo();
          break;
      }
    });
    console.log(e);
  },

  hanldedownLoadImgs() {
    insertHouseMaterialDownLoadLog({
      logType: "0",
      delId: this.data.detailContent.houDelVO.id,
    });

    this.handleHideMoreOptions();
    if (this.data.bannerList && this.data.bannerList.length) {
      let list = [...this.data.bannerList];
      let total = list.length;
      let count = 0;
      p.showLoading({
        title: `保存中${count}/${total}`,
      });
      let save = () => {
        this.saveImageAndroid(list.shift()).then(() => {
          p.showLoading({
            title: `保存中${++count}/${total}`,
          });

          if (list.length) {
            save();
          } else {
            setTimeout(() => {
              p.hideLoading();
              p.showToast({
                title: "图片已保存至手机相册",
                icon: "none",
              });
              api.getMemberPower({
                menuId: "4c75216b479d4ba894e35e14549ca355"
              }, (res) => {
                if (res.data.isSuccess) {
                  wx.setStorageSync("memberInfo", res.data.content.rows);
                }
              });
            }, 200);
          }
        });
      };

      save();
    }
  },

  // 下载房源图片
  hanldeDownLoadImgs(e) {
    if (this.data.statue != 0) {
      this.setData({
        moreDownload: false,
        memberOption: true,
        moreOption: false,
      });
    } else {
      this.hanldedownLoadImgs();
    }
  },

  handleCatch() {},

  handleHideMoreOptions() {
    this.setData({
      showMoreOptions: false,
      moreOption: false,
      moreDownload: false,
      memberOption: false,
    });
  },

  handleMoreOptions() {
    this.setData({
      showMoreOptions: true,
      moreOption: true,
    });
  },

  handleMoreDownload() {
    this.setData({
      showMoreOptions: true,
      moreDownload: true,
    });
  },

  // 下载视频
  videoDown() {
    let that = this;
    that.setData({
      isLoadingHouse: true,
      videoOption: false,
      showMoreOptions: false,
    });
    const downloadTask = wx.downloadFile({
      url: that.data.vrUrl,
      success(res) {
        if (res.statusCode === 200) {
          wx.saveVideoToPhotosAlbum({
            filePath: res.tempFilePath,
            success(ress) {
              console.log(ress);
              wx.showToast({
                title: "保存成功",
              });
              api.getMemberPower({
                menuId: that.data.menuId
              }, (res) => {
                if (res.data.isSuccess) {
                  wx.setStorageSync("memberInfo", res.data.content.rows);
                }
              });
            },
            fail(ref) {
              console.log(ref);
            },
          });
        }
      },
    });
    downloadTask.onProgressUpdate((res) => {
      if (res.progress == 100) {
        that.setData({
          isLoadHouseDone: true,
        });
      }
      console.log("下载进度", res.progress);

      console.log("已经下载的数据长度", res.totalBytesWritten);

      console.log("预期需要下载的数据总长度", res.totalBytesExpectedToWrite);
    });
  },

  videoDownPc() {
    let vrUrl = this.data.vrUrl;
    let that = this;
    wx.setClipboardData({
      data: vrUrl,
      success(res) {
        wx.hideToast();
        wx.showModal({
          content: "视频链接已复制，黏贴到电脑端浏览器即可下载到电脑端",
          showCancel: false,
          confirmText: "我知道了",
          success(res) {
            if (res.confirm) {
              api.getMemberPower({
                menuId: that.data.menuId
              }, (res) => {
                if (res.data.isSuccess) {
                  wx.setStorageSync("memberInfo", res.data.content.rows);
                }
              });
              that.closeVideo();
            }
          },
        });
      },
    });
  },

  // 获取视频连接
  getOssfiles() {
    let that = this;
    api.getOssfiles(
      that.data.detailContent.hmDelSummaryInfo.videoMaterial.videoId,
      (res) => {
        that.setData({
          vrUrl: res.data,
          vrTab: 3,
        });
      }
    );
  },

  vrdownLoad() {
    api.submitVrTask({
        delId: this.data.houdelid,
      },
      (res) => {
        if (res.data.isSuccess) {
          api.getMemberPower({
            menuId: "f18a0d92aec4499f8866cff3d7226c47"
          }, (res) => {
            if (res.data.isSuccess) {
              wx.setStorageSync("memberInfo", res.data.content.rows);
            }
          });
          this.setData({
            showMoreOptions: false,
            memberOption: false,
          });
          wx.showToast({
            title: "VR申请下载成功，预期5分钟后完成下载",
            icon: "none",
          });
          this.getHouseInfo();
        } else {
          wx.showToast({
            title: "VR申请下载失败",
            icon: "none",
          });
          return;
        }
      }
    );
  },

  vrDownLoad() {
    if (this.data.statue != 0) {
      this.setData({
        moreDownload: false,
        memberOption: true,
        moreOption: false,
      });
    } else {
      this.vrdownLoad();
    }
  },

  goTocomposite() {
    this.handleHideMoreOptions();
    wx.navigateTo({
      url: "/pages/house/RentalHouseDetail/composite/composite?type=photo&delId=" +
        this.data.houdelid +
        "&menuId=" +
        this.data.menuId +
        "&delType=" +
        this.data.houseTypes,
    });
  },

  //去合成全景图的页面
  goToComposite() {
    let that = this;
    if (that.data.vr && that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 10) {
      if (this.data.statue != 0) {
        this.setData({
          moreDownload: false,
          memberOption: true,
          moreOption: false,
        });
      } else {
        this.goTocomposite();
      }
    } else if (
      (that.data.vrdown && that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 0) ||
      that.data.detailContent.hmDelSummaryInfo.houSubTypeState == -1
    ) {
      wx.showModal({
        content: "当前房源未下载VR，请先下载VR~",
        confirmText: "下载VR",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          if (res.confirm) {
            let e = {
              currentTarget: {
                dataset: {
                  id: "f18a0d92aec4499f8866cff3d7226c47"
                }
              },
            };
            that.handleMemberDownLoadImgs(e);
          }
        },
      });
    } else if (that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 1) {
      wx.showToast({
        title: "VR正在下载中，请待下载完成后再试",
        icon: "none",
      });
    }
  },

  // 去配音
  goToVoice() {
    // 正在配音则不能重新配音
    if (this.data.detailContent.hmDelSummaryInfo.videoStatus == 1) {
      wx.showToast({
        title: "视频正在合成中，请稍后再试！",
        icon: "none",
      });
      return;
    }

    let that = this;
    if (this.data.detailContent.hmDelSummaryInfo.audioStatus == 0) {
      wx.navigateTo({
        url: "/pages/house/RentalHouseDetail/addAudio/addAudio?required=1&delId=" +
          this.data.houdelid +
          "&delType=" +
          this.data.houseTypes,
      });
    } else {
      wx.showModal({
        content: "该视频已配音，是否需要重新配音",
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/house/RentalHouseDetail/addAudio/addAudio?required=1&delId=" +
                that.data.houdelid +
                "&delType=" +
                that.data.houseTypes,
            });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    }
  },

  goTopanoramagram() {
    this.handleHideMoreOptions();
    wx.navigateTo({
      url: "/pages/house/RentalHouseDetail/panoramagram/panoramagram?delId=" +
        this.data.houdelid +
        "&menuId=" +
        this.data.menuId,
    });
  },

  //去下载全景图的页面
  goToPanoramagram() {
    let that = this;
    if (that.data.vr && that.data.detailContent.hmDelSummaryInfo.notAvailableScenesNum > 0) {
      if (this.data.statue != 0) {
        this.setData({
          moreDownload: false,
          memberOption: true,
          moreOption: false,
        });
      } else {
        this.goTopanoramagram();
      }
    } else if (
      (that.data.vrdown && that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 0) ||
      that.data.detailContent.hmDelSummaryInfo.houSubTypeState == -1
    ) {
      wx.showModal({
        content: "当前房源未下载VR，请先下载VR~",
        confirmText: "下载VR",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          if (res.confirm) {
            let e = {
              currentTarget: {
                dataset: {
                  id: "f18a0d92aec4499f8866cff3d7226c47"
                }
              },
            };
            that.handleMemberDownLoadImgs(e);
          }
        },
      });
    } else if (that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 1) {
      wx.showToast({
        title: "VR正在下载中，请待下载完成后再试",
        icon: "none",
      });
    } else if (
      that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 10 &&
      that.data.detailContent.hmDelSummaryInfo.notAvailableScenesNum == 0 &&
      (that.data.detailContent.hmDelSummaryInfo.sphereStatus == 0 ||
        that.data.detailContent.hmDelSummaryInfo.sphereStatus == -1)
    ) {
      wx.showModal({
        content: "全景图还未合成，请先合成全景图~",
        confirmText: "去合成",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          if (res.confirm) {
            let e = {
              currentTarget: {
                dataset: {
                  id: "60e6298af0b24f9db9af005e11e8e87a"
                }
              },
            };
            that.handleMemberDownLoadImgs(e);
          }
        },
      });
    } else if (that.data.detailContent.hmDelSummaryInfo.sphereStatus == 1) {
      wx.showToast({
        title: "全景图正在合成中，请稍后再试~",
        icon: "none",
      });
    }
  },

  //预览轮播图
  previewBannerImage: function (e) {
    var bannerList = this.data.bannerList,
      current = bannerList[this.data.currentSwiper];
    wx.previewImage({
      current: current,
      urls: bannerList,
    });
  },

  //预览名片
  previewImage: function (e) {
    var image = e.currentTarget.dataset.image;
    var urls = new Array();
    urls.push(image);

    wx.previewImage({
      urls: urls,
    });
  },

  //跳转直接分享----到树懒找房小程序---带各种ID 和房源详情的相关数据
  goShareImage() {
    var allId = {};
    var loginUserInfo = getApp().globalData.loginUserInfo;
    if (loginUserInfo) {
      allId.agentId = loginUserInfo.data.content.sessionUser.id;
      allId.storeId = loginUserInfo.data.content.sessionUser.extProps.storeId;
      allId.mkId = "EMP";
      allId.houDelId = this.data.detailContent.houDelVO.id;
    }

    api.shareHouseLog({
      sourceApp: "0",
      shareType: "1",
      delId: this.data.detailContent.houDelVO.id,
    });

    wx.gio("track", constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
      [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE,
    });

    var extraData = {
      allId: allId,
      type: "coupon",
    };
    extraData.allId.isTranspond = true;
    wx.navigateToMiniProgram({
      appId: "wx5adc5dd9870f6a26", //树懒找房极速版appid
      path: "pages/houseShare/RentalHouseDetailLite/RentalHouseDetailLite?jingjiId=" + JSON.stringify(extraData),
      extraData: extraData,
      envVersion: util.envVersion,
      success: (res) => {
        // 打开成功
        wx.gio("track", constant.SHARE_SUCCESS, {
          [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
          [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
        });
      },
      fail(res) {
        //
      },
    });
  },

  //海报分享
  posterShareImage() {
    api.shareHouseLog({
      sourceApp: "0",
      shareType: "3",
      delId: this.data.detailContent.houDelVO.id,
    });

    wx.gio("track", constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
      [constant.SHARETYPE_VAR]: constant.HB_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE,
    });

    var allId = {};
    var loginUserInfo = getApp().globalData.loginUserInfo;
    const sessionUser = loginUserInfo.data.content.sessionUser;
    allId.agentId = sessionUser.id;
    allId.storeId = sessionUser.extProps.storeId;
    allId.mkId = "EMP";
    allId.houDelId = this.data.detailContent.houDelVO.id;
    allId.realName = sessionUser.realName;
    allId.mobile = sessionUser.mobile;
    allId.wxHeadImg = sessionUser.avatar || sessionUser.extProps.wxHeadImg;

    var extraData = {
      roomDetail: this.data.detailContent,
      allId: allId,
      type: "coupon",
    };

    extraData = JSON.parse(JSON.stringify(extraData));
    Object.assign(extraData.roomDetail, extraData.roomDetail.houDelVO);
    extraData.roomDetail.houDelVO = null;
    app.globalData.houseShareBannerInfo = extraData;
    console.log("app.globalData.houseShareBannerInfo==", app.globalData.houseShareBannerInfo);
    p.navigateTo({
      url: "/pages/house/RentalHouseDetail/oldHouseShare/oldHouseShare"
    });

    wx.gio("track", constant.SHARE_SUCCESS, {
      [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
      [constant.SHARETYPE_VAR]: constant.HB_SHARE,
    });
  },

  friendsShareTabDialog() {
    let that = this;
    that.setData({
      shareShowDialog: false,
      friendsShowDialog: false,
      pyqmodal: false,
      pyqVisible: false,
    });
  },

  //分享到朋友圈，复制关键信息及链接
  goSharepyq() {
    api.shareHouseLog({
      sourceApp: "0",
      shareType: "2",
      delId: this.data.detailContent.houDelVO.id,
    });

    wx.gio("track", constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
      [constant.SHARETYPE_VAR]: constant.PYQ_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE,
    });

    let that = this;
    const houDelVO = that.data.detailContent.houDelVO;
    const priceTitle = houDelVO.delegationType == "SALES" ? '售价' : '租金';
    let price =
      houDelVO.totalPrices == -1 ?
      "暂无售价" :
      houDelVO.delegationType == "SALES" ?
      houDelVO.totalPrices / 10000 + "万" :
      houDelVO.totalPrices + "元/月";
    wx.setClipboardData({
      data: `小区：${houDelVO.resblockName}
户型：${
        houDelVO.room == -1 && houDelVO.hall
          ? "暂无户型"
          : houDelVO.room + "室" + houDelVO.hall + "厅"
      }
面积：${
        houDelVO.buildSize == -1
          ? "暂无面积"
          : houDelVO.buildSize + "m²"
      }
${priceTitle}：${price}
地址：${houDelVO.area ? houDelVO.area + " " : ""}${
        houDelVO.addr
      }`,
      success(res) {
        wx.getClipboardData({
          success(res) {},
        });
      },
    });
    this.setData({
      shareShowDialog: true,
      friendsShowDialog: true,
      pyqVisible: true,
    });
    var loginUserInfo = getApp().globalData.loginUserInfo;
    api.oldHouseInfo({
      agentid: loginUserInfo.data.content.sessionUser.id,
      openid: wx.getStorageSync("aldstat_op"),
    });
  },

  //复制关键信息及链接
  goCopy() {
    let that = this;
    that.setData({
      friendsShowDialog: false,
      shareShowDialog: false,
    });
    let detailContent = this.data.detailContent.houDelVO;
    let userid = getApp().globalData.loginUserInfo.data.content.sessionUser.id;

    let isVr =
      this.data.detailContent.hmDelSummaryInfo.houSubType == 1 &&
      this.data.detailContent.hmDelSummaryInfo.houSubTypeState == 10 ?
      "VR看房 " :
      "";

    let _price = this.getPriceText(detailContent)

    let _size = detailContent.buildSize != -1 && detailContent.buildSize ? detailContent.buildSize + "㎡" : "未填面积";
    let copyText = isVr + detailContent.resblockName + _price + _size;

    var loginUserInfo = getApp().globalData.loginUserInfo;
    let message = {
      touser: wx.getStorageSync("aldstat_op"),
      msgtype: "link",
      link: {
        title: `【${copyText}】分享链接`,
        description: "点击可以分享至朋友圈",
        url: `${util.shareUrl}/noauth/hou/RentalHouseDetail?houDelId=${detailContent.id}&userId=${userid}`,
        thumb_url: that.data.detailContent.houImageVO.length > 0 ?
          that.data.detailContent.houImageVO[0].url : "/images/defaultImgSmall.jpg",
      },
    };
    api.setHouseInfo({
        agentid: loginUserInfo.data.content.sessionUser.id,
        openid: wx.getStorageSync("aldstat_op"),
        message: JSON.stringify(message),
      },
      (res) => {
        console.log("成功发送客服消息", res);

        wx.gio("track", constant.SHARE_SUCCESS, {
          [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
          [constant.SHARETYPE_VAR]: constant.PYQ_SHARE,
        });
      }
    );
  },

  getCount() {
    let that = this;
    api.getCount({
        houDelId: that.data.houdelid,
      },
      (res) => {
        that.setData({
          counts: res.data.content,
        });
      }
    );
  },

  houseUndercarriage() {
    var that = this;
    var delId = that.data.houdelid;
    var state = that.data.detailContent.houDelVO.state;
    var style = that.data.detailContent.houDelVO.delegationType;
    var houseId = that.data.detailContent.houDelVO.houseId;
    if (style == "SALES") {
      var delegationType = "RENT";
    } else {
      delegationType = "SALES";
    }
    api.checkDelegationType({
        houseId: houseId,
        delegationType: delegationType,
      },
      (res) => {
        console.log("res.content", res);
        if (res.data.content.length == 0) {
          wx.navigateTo({
            url: "../houseUndercarriage/houseUndercarriage?delId=" +
              delId +
              "&state=" +
              state +
              "&style=" +
              style +
              "&houseId=" +
              houseId +
              "&invalidType=1",
          });
        } else {
          wx.showModal({
            content: `该房源同时存在一套在${style == "SALES" ? "租" : "售"}房源，是否一起下架？`,
            cancelColor: "#ccc",
            confirmColor: "#f64e4e",
            cancelText: "否",
            confirmText: "是",
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: "../houseUndercarriage/houseUndercarriage?delId=" +
                    delId +
                    "&state=" +
                    state +
                    "&style=both" +
                    "&invalidType=0" +
                    "&houseId=" +
                    houseId,
                });
              } else if (res.cancel) {
                wx.navigateTo({
                  url: "../houseUndercarriage/houseUndercarriage?delId=" +
                    delId +
                    "&state=" +
                    state +
                    "&style=" +
                    style +
                    "&houseId=" +
                    houseId +
                    "&invalidType=1",
                });
              }
            },
          });
        }
      }
    );
  },

  houseReturn() {
    let that = this;
    let id = {
      delId: that.data.houdelid,
      state: "AVAILABLE",
      houseId: that.data.detailContent.houDelVO.houseId,
      invalidType: 1,
    };
    api.houseFail("", id, (res) => {
      wx.showModal({
        content: "该房源已经重新上架是否立即更新？",
        cancelColor: "#ccc",
        confirmColor: "#f64e4e",
        success(res) {
          if (res.confirm) {
            that.goRentalHouseModify();
          } else if (res.cancel) {}
        },
      });
    });
  },

  checkVr(e) {
    this.setData({
      vrTab: e.currentTarget.dataset.tabvr,
      currentSwiper: 0,
    });
  },

  // 跳转vr
  goToVr() {
    const {
      vrUrl
    } = this.data.detailContent.hmDelSummaryInfo
    let agentId = getApp().globalData.loginUserInfo.data.content.sessionUser.id;
    app.globalData.vrHouseInfo = {
      ...this.data.detailContent.houDelVO,
      homeImg: this.data.detailContent.houImageVO[0].url,
    };
    if (this.data.detailContent.hmDelSummaryInfo.houSubTypeState == 1) {
      return wx.showToast({
        title: "VR下载未完成，请稍后再试～",
        icon: "none",
      });
    }

    if (vrUrl && httpUrlCheck(vrUrl)) {
      wx.navigateTo({
        url: `/pages/webView/webView?webViewUrl=${vrUrl}&appName=jjrjs`,
      });
    } else {
      wx.showToast({
        title: "VR播放地址不合法～",
        icon: "none",
      });
    }
  },

  getMemberPower() {
    switch (this.data.menuId) {
      case "4c75216b479d4ba894e35e14549ca355":
        this.setData({
          fn: "下载图片",
        });
        // this.hanldeDownLoadImgs();
        this.hanldedownLoadImgs();
        break;
      case "73ed001b790d4d1cb3e1f74a88756669":
        // this.goToPanoramagram();
        this.goTopanoramagram();
        break;
      case "f18a0d92aec4499f8866cff3d7226c47":
        // this.vrDownLoad();
        // this.hanldedownLoadImgs();
        this.vrdownLoad();
        break;
      case "60e6298af0b24f9db9af005e11e8e87a":
        // this.goToComposite();
        this.goTocomposite();
        break;
      case "5a634e15be20415c854056e30e49545d":
        // this.handleVideo();
        this.handlevideo();
        break;
      case "cb97dc7641fc482c805d42f83661c1c0":
        // this.goToVideo();
        this.goTovideo();
        break;
    }
  },

  goTovideo() {
    let that = this;
    if (that.data.detailContent.hmDelSummaryInfo.videoMaterial) {
      wx.showModal({
        content: "该房源已存在视频，重新合成将替换原视频",
        confirmText: "确定替换",
        confirmColor: "#F75353",
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/house/RentalHouseDetail/composite/composite?type=video&delId=" +
                that.data.houdelid +
                "&required=0&delType=" +
                this.data.detailContent.houDelVO.delegationType,
            });
          } else if (res.cancel) {}
        },
      });
    } else {
      wx.navigateTo({
        url: "/pages/house/RentalHouseDetail/composite/composite?type=video&delId=" +
          that.data.houdelid +
          "&required=0&delType=" +
          this.data.detailContent.houDelVO.delegationType,
      });
    }
  },

  goToVideo() {
    let that = this;
    if (that.data.vr && that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 10) {
      if (that.data.detailContent.hmDelSummaryInfo.videoStatus != 1) {
        if (this.data.statue != 0) {
          this.setData({
            moreDownload: false,
            memberOption: true,
            moreOption: false,
          });
        } else {
          this.goTovideo();
        }
      } else {
        wx.showToast({
          title: "视频正在合成中，请稍后再试！",
          icon: "none",
        });
      }
    } else if (
      (that.data.vrdown && that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 0) ||
      that.data.detailContent.hmDelSummaryInfo.houSubTypeState == -1
    ) {
      wx.showModal({
        content: "当前房源未下载VR，请先下载VR~",
        confirmText: "下载VR",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          if (res.confirm) {
            let e = {
              currentTarget: {
                dataset: {
                  id: "f18a0d92aec4499f8866cff3d7226c47"
                }
              },
            };
            that.handleMemberDownLoadImgs(e);
          }
        },
      });
    } else if (that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 1) {
      wx.showToast({
        title: "VR正在下载中，请待下载完成后再试",
        icon: "none",
      });
    }
  },

  // 播放视频
  playVideo() {
    wx.navigateTo({
      url: "/pages/house/RentalHouseDetail/audioPlayPage/audioPlayPage?src=" + this.data.vrUrl,
    });
  },

  handlevideo() {
    this.setData({
      videoOption: true,
      showMoreOptions: true,
      moreDownload: false,
      memberOption: false,
    });
  },

  handleVideo() {
    let that = this;
    if (that.data.vr && that.data.vrUrl) {
      if (this.data.statue != 0) {
        this.setData({
          moreDownload: false,
          memberOption: true,
          moreOption: false,
        });
      } else {
        this.handlevideo();
      }
    } else if (
      (that.data.vrdown && that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 0) ||
      that.data.detailContent.hmDelSummaryInfo.houSubTypeState == -1
    ) {
      wx.showModal({
        content: "当前房源未下载VR，请先下载VR~",
        confirmText: "下载VR",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          if (res.confirm) {
            let e = {
              currentTarget: {
                dataset: {
                  id: "f18a0d92aec4499f8866cff3d7226c47"
                }
              },
            };
            that.handleMemberDownLoadImgs(e);
          }
        },
      });
    } else if (that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 1) {
      wx.showToast({
        title: "VR正在下载中，请待下载完成后再试",
        icon: "none",
      });
    } else if (
      that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 10 &&
      !that.data.vrUrl &&
      (that.data.detailContent.hmDelSummaryInfo.videoStatus == 0 ||
        that.data.detailContent.hmDelSummaryInfo.videoStatus == -1)
    ) {
      wx.showModal({
        content: "房源视频还未合成，请先合成视频~",
        confirmText: "合成视频",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          if (res.confirm) {
            let e = {
              currentTarget: {
                dataset: {
                  id: "cb97dc7641fc482c805d42f83661c1c0"
                }
              },
            };
            that.handleMemberDownLoadImgs(e);
          }
        },
      });
    } else if (that.data.detailContent.hmDelSummaryInfo.videoStatus == 1) {
      wx.showToast({
        title: "视频正在合成中，请稍后再试~",
        icon: "none",
      });
    }
  },

  closeVideo() {
    this.setData({
      videoOption: false,
      showMoreOptions: false,
    });
  },

  handleLoadHouseDone() {
    this.setData({
      isLoadingHouse: false,
      isLoadHouseDone: false,
    });
  },

  timeoutFn() {
    this.setData({
      isLoadingHouse: false,
    });
    p.showToast({
      title: "下载视频超时！",
      icon: "none",
    });
  },

  handleNavigation() {
    const lat = this.data.detailContent.houDelVO.lat;
    const lng = this.data.detailContent.houDelVO.lng;
    wx.openLocation({
      latitude: Number(lat),
      longitude: Number(lng),
      scale: 16,
    });
  },

  goMapDetails(e) {
    const currentTitle = e.currentTarget.dataset.title;
    const currentTabState = e.currentTarget.dataset.index;
    const lat = this.data.detailContent.houDelVO.lat;
    const lng = this.data.detailContent.houDelVO.lng;
    this.setData({
      currentTabState,
    });

    wx.navigateTo({
      url: `/pages/house/RentalHouseDetail/mapDetails/mapDetails?latitude=${lat}&longitude=${lng}&currentTitle=${currentTitle}&currentTabState=${currentTabState}`,
    });
  },

  checkCooperationStatus(status) {
    if (status) {
      wx.showModal({
        content: '该房源已下架~',
        showCancel: false,
      })
    }
  },

  uploadVisitorLog({
    cooperationId,
    delId
  }) {
    api.addVisitor({
      cooperationId,
      delId
    }, (res) => {})
  },


  // 打假功能
  anti_counterfeit(e) {
    let userid = e.currentTarget.dataset.userid
    let houseid = e.currentTarget.dataset.houseid
    this.dialog = this.selectComponent("#com-counterfeity");
    this.dialog.showDialog()
    this.setData({
      useridTmp: userid,
      houseidTmp: houseid
    })
  },
  cancelEventX(e) {
    let visible = e.detail.visible
    if (visible) {
      this.setData({
        isShowdajiaPng: false
      })
    }
  },

  /* ----------------------------2021-06-20合作房源优化-------------------------------- */
  //  点击展开
  showMore() {
    this.setData({
      showMap: true
    })
  },
  closeMore() {
    this.setData({
      showMap: false
    })
  },
  //查看头像
  lookPicture() {
    wx.gio("track", constant.LOOK_PICTURE, {
      [constant.HOUSE_INFO]: '查看头像',
    });
    let pictureUrls = []
    pictureUrls.push(this.data.jjrVO.avatar)
    wx.previewImage({
      urls: pictureUrls,
    })
  },
  //查看完整的个性宣言
  lookDeclaration() {
    wx.gio("track", constant.LOOK_DECLARATION, {
      [constant.HOUSE_INFO_DECLARATION]: '查看完整的个性宣言',
    });
    wx.showToast({
      title: this.data.jjrVO.declaration,
      icon: 'none',
      duration: 2000
    })
  }
});